<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商家管理 - 外卖平台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: #f5f5f5;
            color: #333;
        }
        
        .header {
            background: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 20px 0;
            margin-bottom: 30px;
        }
        
        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header h1 {
            color: #ff6b6b;
            font-size: 28px;
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }
        
        .btn-primary {
            background: #ff6b6b;
            color: white;
        }
        
        .btn-primary:hover {
            background: #ee5a24;
            transform: translateY(-2px);
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }
        
        .tabs {
            display: flex;
            background: white;
            border-radius: 12px;
            padding: 4px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .tab {
            flex: 1;
            padding: 15px;
            border: none;
            background: transparent;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            color: #666;
            border-radius: 8px;
            transition: all 0.3s ease;
        }
        
        .tab.active {
            background: #ff6b6b;
            color: white;
            box-shadow: 0 2px 10px rgba(255, 107, 107, 0.3);
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
            transition: all 0.3s ease;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        }
        
        .stat-icon {
            font-size: 2.5rem;
            margin-bottom: 15px;
        }
        
        .stat-number {
            font-size: 2rem;
            font-weight: bold;
            color: #ff6b6b;
            margin-bottom: 5px;
        }
        
        .stat-label {
            color: #666;
            font-size: 0.9rem;
        }
        
        .dishes-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        
        .dish-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }
        
        .dish-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        }
        
        .dish-image {
            width: 100%;
            height: 200px;
            border-radius: 8px;
            overflow: hidden;
            margin-bottom: 15px;
        }
        
        .dish-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .dish-info h3 {
            color: #333;
            margin-bottom: 10px;
            font-size: 18px;
        }
        
        .dish-price {
            color: #ff6b6b;
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        
        .dish-category {
            background: #f8f9fa;
            color: #666;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            display: inline-block;
            margin-bottom: 10px;
        }
        
        .dish-description {
            color: #666;
            font-size: 14px;
            line-height: 1.5;
            margin-bottom: 15px;
        }
        
        .dish-actions {
            display: flex;
            gap: 10px;
        }
        
        .edit-btn {
            background: #28a745;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .delete-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .orders-list {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .order-card {
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 15px;
            transition: all 0.3s ease;
        }
        
        .order-card:hover {
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .order-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .order-id {
            font-weight: bold;
            color: #333;
        }
        
        .order-status {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        
        .status-preparing {
            background: #d1ecf1;
            color: #0c5460;
        }
        
        .status-ready {
            background: #d4edda;
            color: #155724;
        }
        
        .status-completed {
            background: #e2e3e5;
            color: #383d41;
        }
        
        .order-content {
            margin-bottom: 15px;
        }
        
        .order-content p {
            margin-bottom: 5px;
            color: #666;
        }
        
        .order-actions {
            display: flex;
            gap: 10px;
        }
        
        .back-btn {
            position: fixed;
            top: 20px;
            left: 20px;
            background: rgba(255, 107, 107, 0.8);
            border: none;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            cursor: pointer;
            color: white;
            font-size: 20px;
            transition: all 0.3s ease;
            z-index: 1000;
        }
        
        .back-btn:hover {
            background: #ff6b6b;
            transform: scale(1.1);
        }
        
        .hidden {
            display: none;
        }
        
        .message {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-weight: 500;
            text-align: center;
        }
        
        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
    </style>
</head>
<body>
    <button class="back-btn" onclick="goBack()">←</button>
    
    <div class="header">
        <div class="header-content">
            <h1>🏪 商家管理后台</h1>
            <div class="user-info">
                <span id="merchantName">商家名称</span>
                <button class="btn btn-secondary" onclick="logout()">退出登录</button>
            </div>
        </div>
    </div>
    
    <div class="container">
        <div id="message"></div>
        
        <div class="tabs">
            <button class="tab active" onclick="showTab('dashboard')">📊 数据概览</button>
            <button class="tab" onclick="showTab('dishes')">🍽️ 菜品管理</button>
            <button class="tab" onclick="showTab('orders')">📋 订单管理</button>
            <button class="tab" onclick="showTab('analytics')">📈 数据分析</button>
            <button class="tab" onclick="showTab('marketing')">🎯 营销工具</button>
            <button class="tab" onclick="showTab('settings')">⚙️ 店铺设置</button>
        </div>
        
        <!-- 数据概览 -->
        <div id="dashboard" class="tab-content active">
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon">📊</div>
                    <div class="stat-number" id="todayOrders">0</div>
                    <div class="stat-label">今日订单</div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">💰</div>
                    <div class="stat-number" id="todayRevenue">¥0</div>
                    <div class="stat-label">今日收入</div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">⭐</div>
                    <div class="stat-number" id="avgRating">0.0</div>
                    <div class="stat-label">平均评分</div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">🍽️</div>
                    <div class="stat-number" id="totalDishes">0</div>
                    <div class="stat-label">菜品数量</div>
                </div>
            </div>
        </div>
        
        <!-- 菜品管理 -->
        <div id="dishes" class="tab-content">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2>菜品管理</h2>
                <button class="btn btn-primary" onclick="goToDishManage()">+ 添加新菜品</button>
            </div>
            <div class="dishes-grid" id="dishesGrid">
                <!-- 菜品将通过JavaScript动态加载 -->
            </div>
        </div>
        
        <!-- 订单管理 -->
        <div id="orders" class="tab-content">
            <h2>订单管理</h2>
            <div class="orders-list" id="ordersList">
                <!-- 订单将通过JavaScript动态加载 -->
            </div>
        </div>
        
        <!-- 数据分析 -->
        <div id="analytics" class="tab-content">
            <h2>数据分析</h2>
            <div class="analytics-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">
                <div class="analytics-card" style="background: white; border-radius: 12px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                    <h3>📊 销售趋势</h3>
                    <div id="salesChart" style="height: 200px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 8px; display: flex; align-items: center; justify-content: center; color: white; font-size: 18px;">
                        销售趋势图
                    </div>
                    <div style="margin-top: 15px;">
                        <p>本周销售额: <span style="color: #ff6b6b; font-weight: bold;">¥2,580</span></p>
                        <p>环比增长: <span style="color: #28a745; font-weight: bold;">+12.5%</span></p>
                    </div>
                </div>
                
                <div class="analytics-card" style="background: white; border-radius: 12px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                    <h3>🍽️ 热门菜品</h3>
                    <div id="popularDishes">
                        <!-- 热门菜品列表 -->
                    </div>
                </div>
                
                <div class="analytics-card" style="background: white; border-radius: 12px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                    <h3>⏰ 订单时段分析</h3>
                    <div id="timeAnalysis" style="height: 200px; background: linear-gradient(135deg, #4ecdc4 0%, #45b7d1 100%); border-radius: 8px; display: flex; align-items: center; justify-content: center; color: white; font-size: 18px;">
                        时段分析图
                    </div>
                    <div style="margin-top: 15px;">
                        <p>高峰时段: <span style="color: #ff6b6b; font-weight: bold;">12:00-13:00</span></p>
                        <p>订单占比: <span style="color: #28a745; font-weight: bold;">35%</span></p>
                    </div>
                </div>
                
                <div class="analytics-card" style="background: white; border-radius: 12px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                    <h3>💰 收益分析</h3>
                    <div style="display: flex; justify-content: space-between; margin-bottom: 15px;">
                        <div>
                            <p style="color: #666; font-size: 14px;">今日收益</p>
                            <p style="color: #ff6b6b; font-size: 24px; font-weight: bold;">¥580</p>
                        </div>
                        <div>
                            <p style="color: #666; font-size: 14px;">本月收益</p>
                            <p style="color: #28a745; font-size: 24px; font-weight: bold;">¥12,580</p>
                        </div>
                    </div>
                    <div style="background: #f8f9fa; border-radius: 8px; padding: 15px;">
                        <p style="margin: 0; color: #666;">平均客单价: <span style="color: #333; font-weight: bold;">¥45</span></p>
                        <p style="margin: 5px 0 0 0; color: #666;">复购率: <span style="color: #333; font-weight: bold;">68%</span></p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 营销工具 -->
        <div id="marketing" class="tab-content">
            <h2>营销工具</h2>
            <div class="marketing-tools" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">
                <div class="marketing-card" style="background: white; border-radius: 12px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                    <h3>🎫 优惠券管理</h3>
                    <div style="margin-bottom: 15px;">
                        <button class="btn btn-primary" onclick="createCoupon()">创建优惠券</button>
                    </div>
                    <div id="couponList">
                        <!-- 优惠券列表 -->
                    </div>
                </div>
                
                <div class="marketing-card" style="background: white; border-radius: 12px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                    <h3>📢 促销活动</h3>
                    <div style="margin-bottom: 15px;">
                        <button class="btn btn-primary" onclick="createPromotion()">创建促销</button>
                    </div>
                    <div id="promotionList">
                        <!-- 促销活动列表 -->
                    </div>
                </div>
                
                <div class="marketing-card" style="background: white; border-radius: 12px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                    <h3>👥 会员管理</h3>
                    <div style="display: flex; justify-content: space-between; margin-bottom: 15px;">
                        <div>
                            <p style="color: #666; font-size: 14px;">总会员数</p>
                            <p style="color: #ff6b6b; font-size: 24px; font-weight: bold;">1,256</p>
                        </div>
                        <div>
                            <p style="color: #666; font-size: 14px;">活跃会员</p>
                            <p style="color: #28a745; font-size: 24px; font-weight: bold;">892</p>
                        </div>
                    </div>
                    <button class="btn btn-secondary" onclick="viewMembers()">查看会员</button>
                </div>
                
                <div class="marketing-card" style="background: white; border-radius: 12px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                    <h3>📱 推送通知</h3>
                    <div style="margin-bottom: 15px;">
                        <textarea placeholder="输入推送内容..." style="width: 100%; height: 80px; border: 1px solid #ddd; border-radius: 8px; padding: 10px; resize: none;"></textarea>
                    </div>
                    <button class="btn btn-primary" onclick="sendNotification()">发送通知</button>
                </div>
            </div>
        </div>
        
        <!-- 店铺设置 -->
        <div id="settings" class="tab-content">
            <h2>店铺设置</h2>
            <div style="background: white; border-radius: 12px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                <div class="settings-section" style="margin-bottom: 30px;">
                    <h3>基本信息</h3>
                    <div class="form-group" style="margin-bottom: 15px;">
                        <label>店铺名称</label>
                        <input type="text" id="shopName" value="美味餐厅" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
                    </div>
                    <div class="form-group" style="margin-bottom: 15px;">
                        <label>店铺地址</label>
                        <input type="text" id="shopAddress" value="北京市朝阳区xxx街道123号" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
                    </div>
                    <div class="form-group" style="margin-bottom: 15px;">
                        <label>联系电话</label>
                        <input type="text" id="shopPhone" value="010-12345678" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
                    </div>
                    <button class="btn btn-primary" onclick="updateShopInfo()">保存设置</button>
                </div>
                
                <div class="settings-section" style="margin-bottom: 30px;">
                    <h3>营业时间</h3>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                        <div>
                            <label>开始时间</label>
                            <input type="time" id="openTime" value="09:00" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
                        </div>
                        <div>
                            <label>结束时间</label>
                            <input type="time" id="closeTime" value="22:00" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
                        </div>
                    </div>
                    <button class="btn btn-primary" onclick="updateBusinessHours()" style="margin-top: 15px;">保存时间</button>
                </div>
                
                <div class="settings-section">
                    <h3>配送设置</h3>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                        <div>
                            <label>配送费</label>
                            <input type="number" id="deliveryFee" value="5" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
                        </div>
                        <div>
                            <label>起送价</label>
                            <input type="number" id="minOrder" value="20" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
                        </div>
                        <div>
                            <label>配送时间(分钟)</label>
                            <input type="number" id="deliveryTime" value="30" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
                        </div>
                    </div>
                    <button class="btn btn-primary" onclick="updateDeliverySettings()" style="margin-top: 15px;">保存设置</button>
                </div>
            </div>
        </div>
    </div>

    <script src="database.js"></script>
    <script>
        let currentUser = null;
        let currentMerchant = null;
        
        // 页面加载时初始化
        window.onload = function() {
            checkLoginStatus();
            loadDashboard();
            loadDishes();
            loadOrders();
            loadAnalytics();
            loadMarketing();
        };
        
        function checkLoginStatus() {
            const savedUser = localStorage.getItem('currentUser');
            if (savedUser) {
                currentUser = JSON.parse(savedUser);
                if (currentUser.type !== 'merchant') {
                    alert('您没有权限访问商家管理页面！');
                    window.location.href = 'home.html';
                    return;
                }
                currentMerchant = db.getMerchantById(currentUser.id);
                document.getElementById('merchantName').textContent = currentUser.name;
            } else {
                alert('请先登录！');
                window.location.href = 'login.html';
            }
        }
        
        function showTab(tabName) {
            // 隐藏所有标签页内容
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            
            // 移除所有标签页的激活状态
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // 显示选中的标签页
            document.getElementById(tabName).classList.add('active');
            
            // 激活对应的标签按钮
            event.target.classList.add('active');
            
            // 根据标签页加载相应数据
            switch(tabName) {
                case 'dashboard':
                    loadDashboard();
                    break;
                case 'dishes':
                    loadDishes();
                    break;
                case 'orders':
                    loadOrders();
                    break;
                case 'analytics':
                    loadAnalytics();
                    break;
                case 'marketing':
                    loadMarketing();
                    break;
            }
        }
        
        function loadDashboard() {
            if (!currentUser) return;
            
            const orders = db.getOrdersByMerchant(currentUser.id);
            const dishes = db.getDishesByMerchant(currentUser.id);
            
            // 计算今日数据
            const today = new Date().toDateString();
            const todayOrders = orders.filter(order => 
                new Date(order.orderTime).toDateString() === today
            );
            
            const todayRevenue = todayOrders.reduce((sum, order) => sum + order.finalPrice, 0);
            const avgRating = dishes.length > 0 ? 
                (dishes.reduce((sum, dish) => sum + dish.rating, 0) / dishes.length).toFixed(1) : 0;
            
            document.getElementById('todayOrders').textContent = todayOrders.length;
            document.getElementById('todayRevenue').textContent = `¥${todayRevenue}`;
            document.getElementById('avgRating').textContent = avgRating;
            document.getElementById('totalDishes').textContent = dishes.length;
        }
        
        function loadDishes() {
            if (!currentUser) return;
            
            const dishes = db.getDishesByMerchant(currentUser.id);
            const dishesGrid = document.getElementById('dishesGrid');
            
            if (dishes.length === 0) {
                dishesGrid.innerHTML = `
                    <div style="grid-column: 1 / -1; text-align: center; padding: 40px; color: #666;">
                        <p>暂无菜品，点击"添加新菜品"开始添加</p>
                    </div>
                `;
                return;
            }
            
            dishesGrid.innerHTML = dishes.map(dish => `
                <div class="dish-card">
                    <div class="dish-image">
                        <img src="${dish.image}" alt="${dish.name}" onerror="this.src='https://via.placeholder.com/300x200?text=菜品图片'">
                    </div>
                    <div class="dish-info">
                        <h3>${dish.name}</h3>
                        <div class="dish-price">¥${dish.price}</div>
                        <div class="dish-category">${dish.category}</div>
                        <div class="dish-description">${dish.description}</div>
                        <div style="margin-bottom: 15px;">
                            <span style="color: #666; font-size: 12px;">评分: ${dish.rating} ⭐</span>
                            <span style="color: #666; font-size: 12px; margin-left: 10px;">销量: ${dish.sales}</span>
                        </div>
                        <div class="dish-actions">
                            <button class="edit-btn" onclick="editDish(${dish.id})">编辑</button>
                            <button class="delete-btn" onclick="deleteDish(${dish.id})">删除</button>
                        </div>
                    </div>
                </div>
            `).join('');
        }
        
        function loadOrders() {
            if (!currentUser) return;
            
            const orders = db.getOrdersByMerchant(currentUser.id);
            const ordersList = document.getElementById('ordersList');
            
            if (orders.length === 0) {
                ordersList.innerHTML = `
                    <div style="text-align: center; padding: 40px; color: #666;">
                        <p>暂无订单</p>
                    </div>
                `;
                return;
            }
            
            ordersList.innerHTML = orders.map(order => `
                <div class="order-card">
                    <div class="order-header">
                        <span class="order-id">订单号: #${order.id}</span>
                        <span class="order-status status-${order.status}">${getStatusText(order.status)}</span>
                    </div>
                    <div class="order-content">
                        <p><strong>客户:</strong> ${order.customerName}</p>
                        <p><strong>电话:</strong> ${order.customerPhone}</p>
                        <p><strong>地址:</strong> ${order.deliveryAddress}</p>
                        <p><strong>菜品:</strong> ${order.dishes.map(dish => `${dish.name} x${dish.quantity}`).join(', ')}</p>
                        <p><strong>总价:</strong> ¥${order.finalPrice}</p>
                        <p><strong>下单时间:</strong> ${order.orderTime}</p>
                        ${order.notes ? `<p><strong>备注:</strong> ${order.notes}</p>` : ''}
                    </div>
                    <div class="order-actions">
                        ${getOrderActions(order.status, order.id)}
                    </div>
                </div>
            `).join('');
        }
        
        function getStatusText(status) {
            const statusMap = {
                'pending': '待处理',
                'preparing': '制作中',
                'ready': '待配送',
                'completed': '已完成'
            };
            return statusMap[status] || status;
        }
        
        function getOrderActions(status, orderId) {
            switch(status) {
                case 'pending':
                    return `<button class="btn btn-primary" onclick="updateOrderStatus(${orderId}, 'preparing')">开始制作</button>`;
                case 'preparing':
                    return `<button class="btn btn-primary" onclick="updateOrderStatus(${orderId}, 'ready')">制作完成</button>`;
                case 'ready':
                    return `<button class="btn btn-primary" onclick="updateOrderStatus(${orderId}, 'completed')">订单完成</button>`;
                default:
                    return '';
            }
        }
        
        function updateOrderStatus(orderId, newStatus) {
            const order = db.updateOrder(orderId, { status: newStatus });
            if (order) {
                showMessage(`订单 #${orderId} 状态已更新为：${getStatusText(newStatus)}`, 'success');
                loadOrders();
                loadDashboard();
            }
        }
        
        function editDish(dishId) {
            // 跳转到菜品管理页面进行编辑
            window.location.href = `dish-manage.html?edit=${dishId}`;
        }
        
        function deleteDish(dishId) {
            if (confirm('确定要删除这个菜品吗？')) {
                db.deleteDish(dishId);
                showMessage('菜品删除成功！', 'success');
                loadDishes();
                loadDashboard();
            }
        }
        
        function goToDishManage() {
            window.location.href = 'dish-manage.html';
        }
        
        function showMessage(text, type) {
            const messageDiv = document.getElementById('message');
            messageDiv.innerHTML = `<div class="message ${type}">${text}</div>`;
            setTimeout(() => {
                messageDiv.innerHTML = '';
            }, 3000);
        }
        
        function logout() {
            localStorage.removeItem('currentUser');
            window.location.href = 'home.html';
        }
        
        function goBack() {
            window.location.href = 'home.html';
        }
        
        // 数据分析功能
        function loadAnalytics() {
            if (!currentUser) return;
            
            const dishes = db.getDishesByMerchant(currentUser.id);
            const orders = db.getOrdersByMerchant(currentUser.id);
            
            // 加载热门菜品
            loadPopularDishes(dishes);
        }
        
        function loadPopularDishes(dishes) {
            const popularDishesDiv = document.getElementById('popularDishes');
            if (!popularDishesDiv) return;
            
            // 按销量排序
            const sortedDishes = dishes.sort((a, b) => b.sales - a.sales).slice(0, 5);
            
            popularDishesDiv.innerHTML = sortedDishes.map((dish, index) => `
                <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px solid #eee;">
                    <div style="display: flex; align-items: center;">
                        <span style="background: #ff6b6b; color: white; border-radius: 50%; width: 20px; height: 20px; display: flex; align-items: center; justify-content: center; font-size: 12px; margin-right: 10px;">${index + 1}</span>
                        <span>${dish.name}</span>
                    </div>
                    <span style="color: #ff6b6b; font-weight: bold;">${dish.sales}份</span>
                </div>
            `).join('');
        }
        
        // 营销工具功能
        function loadMarketing() {
            loadCoupons();
            loadPromotions();
        }
        
        function loadCoupons() {
            const couponList = document.getElementById('couponList');
            if (!couponList) return;
            
            const coupons = JSON.parse(localStorage.getItem('coupons') || '[]');
            
            if (coupons.length === 0) {
                couponList.innerHTML = '<p style="color: #666; text-align: center; padding: 20px;">暂无优惠券</p>';
                return;
            }
            
            couponList.innerHTML = coupons.map(coupon => `
                <div style="border: 1px solid #eee; border-radius: 8px; padding: 15px; margin-bottom: 10px;">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <h4 style="margin: 0 0 5px 0;">${coupon.name}</h4>
                            <p style="margin: 0; color: #666; font-size: 14px;">${coupon.description}</p>
                        </div>
                        <div style="text-align: right;">
                            <p style="margin: 0; color: #ff6b6b; font-weight: bold;">${coupon.discount}</p>
                            <p style="margin: 0; color: #666; font-size: 12px;">已使用: ${coupon.used}/${coupon.limit}</p>
                        </div>
                    </div>
                </div>
            `).join('');
        }
        
        function loadPromotions() {
            const promotionList = document.getElementById('promotionList');
            if (!promotionList) return;
            
            const promotions = JSON.parse(localStorage.getItem('promotions') || '[]');
            
            if (promotions.length === 0) {
                promotionList.innerHTML = '<p style="color: #666; text-align: center; padding: 20px;">暂无促销活动</p>';
                return;
            }
            
            promotionList.innerHTML = promotions.map(promotion => `
                <div style="border: 1px solid #eee; border-radius: 8px; padding: 15px; margin-bottom: 10px;">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <h4 style="margin: 0 0 5px 0;">${promotion.name}</h4>
                            <p style="margin: 0; color: #666; font-size: 14px;">${promotion.description}</p>
                        </div>
                        <div style="text-align: right;">
                            <span style="background: ${promotion.status === 'active' ? '#28a745' : '#6c757d'}; color: white; padding: 2px 8px; border-radius: 12px; font-size: 12px;">${promotion.status === 'active' ? '进行中' : '已结束'}</span>
                        </div>
                    </div>
                </div>
            `).join('');
        }
        
        function createCoupon() {
            const name = prompt('请输入优惠券名称：');
            if (!name) return;
            
            const discount = prompt('请输入折扣（如：满30减5）：');
            if (!discount) return;
            
            const limit = prompt('请输入使用次数限制：');
            if (!limit) return;
            
            const coupon = {
                id: Date.now(),
                name: name,
                discount: discount,
                description: `满减优惠券`,
                limit: parseInt(limit),
                used: 0,
                status: 'active',
                createTime: new Date().toLocaleString()
            };
            
            const coupons = JSON.parse(localStorage.getItem('coupons') || '[]');
            coupons.push(coupon);
            localStorage.setItem('coupons', JSON.stringify(coupons));
            
            showMessage('优惠券创建成功！', 'success');
            loadCoupons();
        }
        
        function createPromotion() {
            const name = prompt('请输入促销活动名称：');
            if (!name) return;
            
            const description = prompt('请输入活动描述：');
            if (!description) return;
            
            const promotion = {
                id: Date.now(),
                name: name,
                description: description,
                status: 'active',
                createTime: new Date().toLocaleString()
            };
            
            const promotions = JSON.parse(localStorage.getItem('promotions') || '[]');
            promotions.push(promotion);
            localStorage.setItem('promotions', JSON.stringify(promotions));
            
            showMessage('促销活动创建成功！', 'success');
            loadPromotions();
        }
        
        function viewMembers() {
            showMessage('会员管理功能开发中...', 'success');
        }
        
        function sendNotification() {
            const textarea = document.querySelector('textarea');
            const content = textarea.value.trim();
            
            if (!content) {
                showMessage('请输入推送内容！', 'error');
                return;
            }
            
            showMessage('推送通知发送成功！', 'success');
            textarea.value = '';
        }
        
        // 店铺设置功能
        function updateShopInfo() {
            const name = document.getElementById('shopName').value;
            const address = document.getElementById('shopAddress').value;
            const phone = document.getElementById('shopPhone').value;
            
            if (currentMerchant) {
                db.updateUser(currentUser.id, {
                    name: name,
                    restaurantInfo: {
                        ...currentMerchant.restaurantInfo,
                        name: name,
                        address: address,
                        phone: phone
                    }
                });
                
                showMessage('店铺信息更新成功！', 'success');
            }
        }
        
        function updateBusinessHours() {
            const openTime = document.getElementById('openTime').value;
            const closeTime = document.getElementById('closeTime').value;
            
            if (currentMerchant) {
                db.updateUser(currentUser.id, {
                    restaurantInfo: {
                        ...currentMerchant.restaurantInfo,
                        openTime: `${openTime}-${closeTime}`
                    }
                });
                
                showMessage('营业时间更新成功！', 'success');
            }
        }
        
        function updateDeliverySettings() {
            const deliveryFee = document.getElementById('deliveryFee').value;
            const minOrder = document.getElementById('minOrder').value;
            const deliveryTime = document.getElementById('deliveryTime').value;
            
            if (currentMerchant) {
                db.updateUser(currentUser.id, {
                    restaurantInfo: {
                        ...currentMerchant.restaurantInfo,
                        deliveryFee: parseInt(deliveryFee),
                        minOrder: parseInt(minOrder),
                        deliveryTime: `${deliveryTime}分钟`
                    }
                });
                
                showMessage('配送设置更新成功！', 'success');
            }
        }
    </script>
</body>
</html>
